package wh.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;

import wh.bos.utils.MailUtils;
import wh.crm.domain.Customer;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{

		@Action(value="customer_sendSms")
		//短信发送
		public String sendSms(){
			//生成短信验证码
			String randomCode = RandomStringUtils.randomNumeric(4);
			//将短信验证码放到session中
			ServletActionContext.getRequest().getSession().setAttribute(model.getTelephone(), randomCode);
			System.out.println("短信验证码为:"+randomCode);
			//编辑短信内容
			String msg = "尊敬的用户你好,本次验证码为:"+randomCode+",服务电话:12345678";
			//调用Sms发送短信
			String result = "000/1234";
			if (result.startsWith("000")) {
				//发送成功
				return NONE;
			}else{
				//发送失败
				throw new RuntimeException("短信发送失败,信息码:"+result);
			}
			
		}		

			
		//属性驱动
		private String 	checkcode;

		public void setCheckcode(String checkcode) {
			this.checkcode = checkcode;
		}
		//模型驱动
		@Autowired
		private RedisTemplate<String, String> redisTemplate;
			
		
		@Action(value="customer_regist",results={
				@Result(name="success",type="redirect",location="signup-success.html"),
				@Result(name="input",type="redirect",location="signup.html")
				})
		/**
		 * 注册验证
		 * @return
		 */
		public String regist(){
			//先校验短信验证码,如果不通过,调回注册页面
			String checkCodeSession = (String) ServletActionContext.getRequest().getSession().getAttribute(model.getTelephone());
			if (checkCodeSession == null || !checkCodeSession.equals(checkcode)) {
				//验证失败
				System.out.println("短信验证错误");
				return INPUT;
			}
			//调用webService连接CRM保存用户
			WebClient.create("http://localhost:9003/services/customerService/savecustomer")
			.type(MediaType.APPLICATION_JSON).post(model);
			System.out.println("客户注册成功");
			
			//发送一封激活邮件
				//生成激活码
			String activecode = RandomStringUtils.randomNumeric(32);
			//将激活码保存到redis,设置24h失效
			 redisTemplate.opsForValue().set(model.getTelephone(),activecode,24,TimeUnit.HOURS);
			//调用MailUtils发送邮件
			 String content =  "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
						+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
						+ "&activecode=" + activecode + "'>速运快递邮箱绑定地址</a>";
			 MailUtils.sendMail(activecode, content, model.getEmail());
			 return SUCCESS;
			
		}
		//属性驱动
		private String activecode;
		
		public void setActivecode(String activecode) {
			this.activecode = activecode;
		}

		@Action(value="customer_activeEmail")
		//邮箱激活
		public String activeEmail() throws IOException{
			ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
			//判断验证码是否有效
			String activecodeRedis = redisTemplate.opsForValue().get(model.getTelephone());
			if (activecodeRedis == null || !activecodeRedis.equals(activecode)) {
				//激活码无效
				ServletActionContext.getResponse().getWriter().println("激活码无效,请登录系统,重新绑定邮箱");
			}else {
				//激活码有效
				//防止重复绑定
				//调用webservice查询客户端,判断是否已经绑定
				  Customer customer = WebClient.create
				  ("http://localhost:9003/services/customerService/telephone/"+model.getTelephone())
				  .accept(MediaType.APPLICATION_JSON).get(Customer.class);
				  if (customer.getType() == null || customer.getType() != 1) {
					  //没有绑定,进行绑定
					  WebClient.create
					  ("http://localhost:9003/services/customerService/updateType/"+model.getTelephone())
					  .put(null);
				}else {
					//已经绑定,提示不要重复绑定
					ServletActionContext.getResponse().getWriter().println("邮箱已经绑定,请勿重复绑定");
				}
				  //删除Redis中的激活码
				  redisTemplate.delete(model.getTelephone());
			}
			
			return NONE;
		}
		//登录操作
		@Action(value="customer_login",results={
				@Result(name="login",location="login.html",type="redirect"),
				@Result(name="success",location="index.html#/myhome",type="redirect")})
		public String login(){
			Customer customer = WebClient.create("http://localhost:9003/services/customerService/login?telephone="
					+model.getTelephone()+"&password="+model.getPassword())
			.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if (customer==null) {
				return LOGIN;
			}else {
				ServletActionContext.getRequest().getSession().setAttribute("Customer", customer);
				return SUCCESS;
			}
			
		}
		
		
}
